package com.example.video.util;

import java.net.*;
import java.io.*;

public class SuffixUtil {
    public static String getSuffix(String url) {
        try {
            String imageSuffix = determineSuffix(url);

//            log.info("Image URL: " + url);
//            log.info("Image suffix: " + imageSuffix);
            return imageSuffix;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    // 根据 URL 获取 Content-Type 头部字段并解析出文件后缀
    private static String determineSuffix(String urlString) throws IOException {
        URL url;
        try {
            url = new URL(urlString);
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        }

        // 打开连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("HEAD"); // 发送 HEAD 请求

        // 获取 Content-Type 头部字段
        String contentType = connection.getContentType();

        // 解析 MIME 类型并确定后缀
        String suffix = determineSuffix11(contentType);

        return suffix;
    }

    // 根据 MIME 类型确定文件后缀
    private static String determineSuffix11(String contentType) {
        if (contentType == null) {
            return null;
        }

        if (contentType.startsWith("image/jpeg")) {
            return ".jpg";
        } else if (contentType.startsWith("image/png")) {
            return ".png";
        } else if (contentType.startsWith("video/mp4")) {
            return ".mp4";
        } else if (contentType.startsWith("image/webp")) {
            return ".webp";
        }

        // 处理其他 MIME 类型...

        return null;
    }
}
